<?php
namespace app\index\controller;

use think\Controller;
use think\View;

class Index extends Common {
    /**
     * 获取首页数据
     * @return \think\response\View
     */
    public function index() {
        // 首页行业动态 - 推荐位
        $index_list = model('article')->where('index', 1)->where('delete', 0)->order('create_time desc')->limit(3)->select();
        $this->assign('index_list', $index_list);
        $ids = model('article')->where('index', 1)->where('delete', 0)->order('create_time desc')->limit(3)->column('id');

        // 首页新闻中心
        $xwzx = model('article')->where('id', 'not in', $ids)->where('category_id', 2)->where('delete', 0)->order('create_time desc')->limit(5)->select();
        $this->assign('xwzx', $xwzx);

        // 首页行业动态 - 列表
        $hydt = $this->get_index_category_by_pid(1, 5, 7);
        $this->assign('hydt', $hydt);

        // 首页地州频道
        $dzpd = $this->get_index_category_by_pid(7, 6, 7);
        $this->assign('dzpd', $dzpd);

        // 信息发布
        $xxfb = model('article')->where('category_id', 'neq', 2)->whereOr('category_id = 2 && `index` = 1')->where('delete', 0)->order('`index` desc, create_time desc')->limit(14)->select();
        $this->assign('xxfb', $xxfb);

        $data = model('download')->where(['delete' => 0])->order('create_time desc')->limit(5)->select();
        foreach($data as $k => $v){
            $data[$k]['title'] = mb_substr($v['title'], 0, 17, 'UTF-8');
        }
        $this->assign('data', $data);

        return view();
    }

    /**
     * 根据父级ID获取首页显示分分类和文章
     * @param $pid
     * @param $cat_num
     * @param $article_num
     * @return \think\response\View
     */
    public function get_index_category_by_pid($pid, $cat_num, $article_num) {
        $data = model('category')->where('pid', $pid)->where('index', 1)->where('delete', 0)->order('sort desc, id desc')->limit($cat_num)->select();
        foreach ($data as $k => $v) {
            $data[$k]['list'] = $v->article()->where('delete', 0)->order('create_time desc')->limit($article_num)->select();
        }
        return $data;
    }

    public function test() {
        $data = model('article')->all();
        foreach ($data as $v) {
            $day = rand(40, 60);
            $time = time() - $day * 24 * 60 * 60;
            model('article')->save(['create_time' => $time], ['id' => $v->id]);
        }
    }
}
